﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using ClassLibrary.Data;
using System.Collections.Generic;
using ClassLibrary.DAO;
using ClassLibrary.Utilities;

public partial class MuaHang : System.Web.UI.Page
{
    TblCustomersDAO customerDAO = new TblCustomersDAO(Global.CONNECTION_STRING);
    TblBookingDAO bookDAO = new TblBookingDAO(Global.CONNECTION_STRING);

    protected void Page_Load(object sender, EventArgs e)
    {
        lblCheckOutInfo.Text = "";
        try
        {
            if (!IsPostBack)
            {
                LoadData();
            }
        }
        catch (Exception ex)
        {
            Session[Global.SESSION_ERROR] = ex;
        }
    }

    private void LoadData()
    {
        int iNoOfItems = LoadCart();
        decimal dTotalAmount = SetTotalAmount();
        ScriptManager.RegisterStartupScript(grdShoppingCart, grdShoppingCart.GetType(), "ScriptUpdateParents", "UpdateParentsCart('" + iNoOfItems.ToString() + "|" + dTotalAmount.ToString("0,00.##") + "');", true);

        if (Session[Global.SESSION_CART] == null)
            pnlCartFooter.Visible = false;
    }
    private int LoadCart()
    {
        try
        {
            //ArrayList arrItems = (ArrayList)Session[Global.SESSION_CART];


            List<TblBookingDetail> arrItems = new List<TblBookingDetail>();
            if (Session[Global.SESSION_CART] != null)
                arrItems = (List<TblBookingDetail>)Session[Global.SESSION_CART];

            int iNoOfItems = 0;
            decimal dTotalAmount = 0;

            foreach (TblBookingDetail order in arrItems)
            {
                iNoOfItems += order.Quantity;
                //dTotalAmount += order.TotalAmount;
                dTotalAmount += Convert.ToDecimal(order.Quantity * order.Price);
               // lbchip.Text = order.IDChip.ToString();
                lbchip.Text = order.Chip.ChipName.ToString();
            }
            SetNumberOfItems(iNoOfItems);

            grdShoppingCart.DataSource = arrItems;
            grdShoppingCart.DataBind();

            return iNoOfItems;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    private void SetNumberOfItems(int ItemsNumber)
    {
        lblNumber.Text = ItemsNumber.ToString() + " sản phẩm";
        //pnlCartFooter.Visible = true;
        if (ItemsNumber == 0)
        {
            tdShoppingCart.Attributes["class"] = "shoppingCartEmptyS";
            //pnlCartFooter.Visible = false;
        }
        if (ItemsNumber == 1)
        {
            lblNumber.Text = ItemsNumber.ToString() + " sản phẩm";
            tdShoppingCart.Attributes["class"] = "shoppingCartHalfS";
        }
        if (ItemsNumber == 2)
            tdShoppingCart.Attributes["class"] = "shoppingCartFullS";
        if (ItemsNumber > 2)
            tdShoppingCart.Attributes["class"] = "shoppingCartFullMoreS";
    }
    private decimal SetTotalAmount()
    {
        try
        {
            decimal dTotalAmount = 0;
            for (int i = 0; i < grdShoppingCart.Rows.Count; i++)
            {
                Label lblSubTotal = (Label)grdShoppingCart.Rows[i].Cells[4].FindControl("lblSubTotal");
                if (lblSubTotal != null)
                {
                    try
                    {
                        dTotalAmount += Convert.ToDecimal(lblSubTotal.Text.Trim());
                    }
                    catch (Exception) { }
                }
            }

            lblTotal.Text = dTotalAmount.ToString("0,00.##");

            Session[Global.SESSION_TOTAL] = dTotalAmount;

            return dTotalAmount;

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    private static void BindGridView(GridViewRow gridViewRow)
    {
        Label lblPrice = (Label)gridViewRow.Cells[2].FindControl("lblPrice");
        Label lblMatchedPrice = (Label)gridViewRow.Cells[2].FindControl("lblMatchedPrice");
        TextBox txtQuantity = (TextBox)gridViewRow.Cells[3].FindControl("txtQuantity");
        Label lblSubTotal = (Label)gridViewRow.Cells[4].FindControl("lblSubTotal");

        double dPrice = 0;
        double dMatchedPrice = 0;
        int iQuantity = 0;
        try
        {
            dPrice = Convert.ToDouble(lblPrice.Text.Trim().Replace("$", ""));
            dMatchedPrice = Convert.ToDouble(lblMatchedPrice.Text.Trim().Replace("$", ""));
            iQuantity = Convert.ToInt16(txtQuantity.Text.Trim());
        }
        catch (Exception) { }
        double dSubTotal = 0;

        lblPrice.Text = dPrice.ToString("0,00.##");
        if (dMatchedPrice == 0)
        {
            dSubTotal = dPrice * iQuantity;
            lblPrice.Text = dPrice.ToString("0,00.##");
            lblMatchedPrice.Visible = false;
        }
        else
        {
            dSubTotal = dMatchedPrice * iQuantity;
            lblPrice.CssClass = "clsPriceCartCrossed";
            lblMatchedPrice.Text = "\r\n" + dMatchedPrice.ToString("0,00.##");
            lblMatchedPrice.Visible = true;
        }

        lblSubTotal.Text = dSubTotal.ToString("0,00.##");

        if (gridViewRow.RowType == DataControlRowType.DataRow)
        {
            //ImageButton imgButton = (ImageButton)gridViewRow.Cells[5].FindControl("imgDelete");
            //gridViewRow.Attributes["onmouseover"] = "$('#" + imgButton.ClientID + "').show();";
            //gridViewRow.Attributes["onmouseout"] = "$('#" + imgButton.ClientID + "').hide();";
        }
    }

    protected void grdShoppingCart_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        try
        {
            GridViewRow gridViewRow = e.Row;
            BindGridView(gridViewRow);
        }
        catch (Exception ex)
        {
            Session[Global.SESSION_ERROR] = ex;
        }
    }
 
    protected void txtQuantity_TextChanged(object sender, EventArgs e)
    {
        bool flag = false;
        
        try
        {
            TextBox txtQuantity = (TextBox)sender;
            if (txtQuantity != null)
            {
                string strUniqueID = txtQuantity.UniqueID;
                int iRowIndex = (Convert.ToInt16(strUniqueID.Split('$')[1].Replace("ctl", "")) - 2);
                GridViewRow gridRow = grdShoppingCart.Rows[iRowIndex];
                if (gridRow != null)
                {
                    int iNoOfItems = 0;
                    if (Session[Global.SESSION_CART] != null)
                    {
                        List<TblBookingDetail> arrProducts = (List<TblBookingDetail>)Session[Global.SESSION_CART];
                        TblBookingDetail order = arrProducts[iRowIndex];

                        string strQuantity = txtQuantity.Text.Trim();
                        int iQuantity = order.Quantity;
                        try
                        {
                            iQuantity = Convert.ToInt16(txtQuantity.Text.Trim());
                            if (iQuantity <= 0)
                                iQuantity = order.Quantity;
                        }
                        catch (Exception) { }

                        txtQuantity.Text = iQuantity.ToString();

                        BindGridView(gridRow);

                        order.Quantity = iQuantity;

                        //Set number of items       
                        for (int i = 0; i < arrProducts.Count; i++)
                        {
                            TblBookingDetail pOrder = (TblBookingDetail)arrProducts[i];
                            iNoOfItems += pOrder.Quantity;
                        }
                        SetNumberOfItems(iNoOfItems);
                    }

                    decimal dTotalAmount = SetTotalAmount();

                    flag = true;
                   // ScriptManager.RegisterStartupScript(grdShoppingCart, grdShoppingCart.GetType(), "ScriptUpdateParents", "UpdateParentsCart('" + iNoOfItems.ToString() + "|" + dTotalAmount.ToString("0,00.##") + "');", true);
                }
            }
        }
        catch (Exception ex)
        {
            Session[Global.SESSION_ERROR] = ex;
        }
        if (flag)
        {
            Response.Redirect("~/MuaHang.aspx");
        }
    }


    protected void imgDelete_Click(object sender, ImageClickEventArgs e)
    {
        try
        {
            ImageButton imgDel = (ImageButton)sender;
            if (imgDel != null)
            {
                string strUniqueID = imgDel.UniqueID;
                int iRowIndex = (Convert.ToInt16(strUniqueID.Split('$')[1].Replace("ctl", "")) - 2);
                if (Session[Global.SESSION_CART] != null)
                {
                    List<TblBookingDetail> arrProducts = (List<TblBookingDetail>)Session[Global.SESSION_CART];
                    //ScriptManager.RegisterStartupScript(pnlShoppingCart, pnlShoppingCart.GetType(), "scriptalert", "alert('" + iRowIndex.ToString() + "');", true);                 
                    arrProducts.RemoveAt(iRowIndex);
                    int iNoOfItems = LoadCart();
                    decimal dTotalAmount = SetTotalAmount();

                    ScriptManager.RegisterStartupScript(grdShoppingCart, grdShoppingCart.GetType(), "ScriptUpdateParents", "UpdateParentsCart('" + iNoOfItems.ToString() + "|" + dTotalAmount.ToString("0,00.##") + "');", true);
                }
            }
        }
        catch (Exception ex)
        {
            Session[Global.SESSION_ERROR] = ex;
            Response.Redirect(Global.ERROR_PAGE, true);
        }
    }

    private bool UserAccount_CheckExists()
    {
        bool bExists = false;
        try
        {
            bExists = customerDAO.CheckExits(txtemail.Text, 1);

        }
        catch (Exception ex)
        {
            Session[Global.SESSION_ERROR] = ex;
            Response.Redirect("~/Error.aspx", true);
        }
        return bExists;
    }
 
    protected void btnBuy_Click(object sender, EventArgs e)
    {
        bool flag = false;
        if (UserAccount_CheckExists())
        {
            //lblMessage.Text = "Email Exist.";
            ScriptManager.RegisterStartupScript(btnBuy, btnBuy.GetType(), "alert", "alert('Email Exist!');", true);
            return;
        }

        if ((Session[Global.SESSION_TOTAL] == null) || (Session[Global.SESSION_CART] == null))
        {
            Response.Redirect("~/index.aspx");
        }

        try
        {
            #region insert customer

            TblCustomers customer = new TblCustomers();
            customer.FName = txtFName.Text;
            customer.LName = txtLName.Text;
            customer.Company = txtcompany.Text;
            customer.CusAddress = txtaddress.Text;
            customer.EmailAdress = txtemail.Text;
            customer.HomePhone = "";
            customer.MobilePhone = txtmobilephone.Text;
            customer.IsAdmin = false;
            customer.WorkPhone = "";
            customer.Password = Encryption.EncryptToString(txtPass.Text);

            String id = Request.QueryString["id"];

            DataTable dt = null;

            if (id == "" || id == null)
            {
                customer.CusID = 0;
                dt = customerDAO.Insert_Up(customer, 1);

                foreach (DataRow dr in dt.Rows)
                {
                    customer.CusID = Convert.ToInt32(dr["CusID"].ToString());
                }
            }
            else
            {
                customer.CusID = Global.ConvertToInt(id);
                customerDAO.Insert_Up(customer, 2);
            }

            #endregion

            #region insert booking
            try
            {
                TblBookingDAO bookingDAO = new TblBookingDAO(Global.CONNECTION_STRING);
                TblBooking booking = new TblBooking();

                booking.CusID = customer.CusID;

                booking.DateBook = DateTime.Now;
                booking.Status = 0;

                if (rdchuyenkhoan.Checked == true)
                {
                    booking.PaymentMethod = 1;
                }
                else
                {
                    booking.PaymentMethod = 2;
                }

                booking.IDType = 2; // Facbook Chip


                booking.TotalPrice = Decimal.Parse(Session[Global.SESSION_TOTAL].ToString());

                List<TblBookingDetail> arrItems = (List<TblBookingDetail>)Session[Global.SESSION_CART];
                int id1;

                bookingDAO.Insert(booking, arrItems, out id1);

                Session[Global.SESSION_CART] = null;
                Session[Global.SESSION_TOTAL] = null;


            }
            catch (Exception ex)
            {
                Session[Global.SESSION_ERROR] = ex;
                Response.Redirect(Global.ERROR_PAGE, true);
            }

            #endregion

            flag = true;

        }
        catch (Exception ex)
        {
            Session[Global.SESSION_ERROR] = ex;
            Response.Redirect(Global.ERROR_PAGE, true);
        }
        if (flag)
        {
            Response.Redirect("~/index.aspx");
        }
    }
}
